package com.qingcheng.handler;

import com.alibaba.fastjson.JSON;
import com.qingcheng.pojo.goods.TbSku;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName InsElasticSearchHandler
 * @Description
 * @Author Simon
 * @Date 2020/8/20 9:33
 * @Version 1.0
 **/
@Component
public class InsElasticSearchHandler {

    @Resource
    private RestHighLevelClient restHighLevelClient; //高级客户端对象

    /**
     * 批量管理es数据
     * @param tbSkus
     * @throws IOException
     */
    public void insOrDel(List<TbSku> tbSkus,String args) throws IOException {
        // 封装请求对象
        BulkRequest bulkRequest=new BulkRequest();
        // 批量处理es数据
        for(TbSku sku : tbSkus) {
            IndexRequest indexRequest = new IndexRequest("sku15", "doc", sku.getId());
            DeleteRequest deleteRequest = new DeleteRequest("sku15", "doc", sku.getId());
            if (args == "ins") {
                Map skuMap = new HashMap();
                skuMap.put("name", sku.getName());
                skuMap.put("brandName", sku.getBrandName());
                skuMap.put("categoryName", sku.getCategoryName());
                skuMap.put("spuId",sku.getSpuId());
                skuMap.put("price", sku.getPrice());
                skuMap.put("image", sku.getImage());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date createTime = sku.getCreateTime();
                if(createTime!=null)
                    skuMap.put("createTime", sdf.format(sku.getCreateTime()));
                else
                    skuMap.put("createTime", null);
                skuMap.put("saleNum", sku.getSaleNum());
                skuMap.put("commentNum", sku.getCommentNum());
                // 新增/修改都需要将数据转换为json
                Map spec = JSON.parseObject(sku.getSpec(), Map.class);
                skuMap.put("spec", spec);
                // 新增需要添加的数据
                indexRequest.source(skuMap);
                bulkRequest.add(indexRequest);//可以多次添加
            } else {
                bulkRequest.add(deleteRequest);
            }
        }
        //3.获取响应结果
        BulkResponse response =
                restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        int status = response.status().getStatus();
        System.out.println(status);
        String message = response.buildFailureMessage();
        System.out.println(message);
        /*try {
            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 缓存预热，项目出事之前执行的事件
     * 传过来的数据是从redis缓存中获取的，默认存储的格式为 ArrayList<LinkedHashMap>
     *              -----
     *     thermalLoading && insOrDel
     *     处理缓存预热        处理上下架
     *     LinkedHashMap     TbSku
     *
     * 如果都用一个方法则会向外抛出转换异常
     * @param skus
     */
    public void thermalLoading (ArrayList<LinkedHashMap> skus) throws IOException {
        // 封装请求对象
        BulkRequest bulkRequest=new BulkRequest();
        for (LinkedHashMap map :
                skus){
            IndexRequest indexRequest = new IndexRequest("sku15", "doc", map.get("id").toString());
            Map skuMap = new HashMap();
            skuMap.put("name", map.get("name"));
            skuMap.put("brandName", map.get("brandName"));
            skuMap.put("spuId",map.get("spuId"));
            skuMap.put("categoryName", map.get("categoryName"));
            skuMap.put("price", map.get("price"));
            skuMap.put("image", map.get("image"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date createTime = null;
            try {
                createTime = sdf.parse(String.valueOf(map.get("createTime")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(createTime!=null)
                skuMap.put("createTime", sdf.format(createTime));
            else
                skuMap.put("createTime", null);
            skuMap.put("saleNum", map.get("saleNum"));
            skuMap.put("commentNum", map.get("commentNum"));
            // 新增/修改都需要将数据转换为json
            Map spec = JSON.parseObject(map.get("spec").toString(), Map.class);
            skuMap.put("spec", spec);
            // 新增需要添加的数据
            indexRequest.source(skuMap);
            bulkRequest.add(indexRequest);//可以多次添加
        }
        //3.获取响应结果

        BulkResponse response =
                restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        int status = response.status().getStatus();
        System.out.println(status);
        String message = response.buildFailureMessage();
        System.out.println(message);
        /*try {
            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

}
